<template>
  <div class="address-edit-box">
    <s-header :name="`${type == 'add' ? '新增地址' : '编辑地址'}`"></s-header>
    <van-address-edit
      class="edit"
      :area-list="areaList"
      :address-info="addressInfo"
      :show-delete="type == 'edit'"
      show-set-default
      show-search-result
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
    />

  </div>
</template>

<script>
import {Toast} from 'vant'
import sHeader from '@/components/SimpleHeader'
import {tdist} from '@/common/js/utils'

export default {
  components: {
    sHeader
  },
  data() {
    return {
      id: '',
      areaList: {
        province_list: {},
        city_list: {},
        county_list: {}
      },
      searchResult: [],
      type: 'add',
      addressId: '',
      addressInfo: {},
      from: '',
      defaultID: '',
      name: '',
      tel: '',
      province_name: '',
      city_name: '',
      region_name: '',
      detail_address: '',
    }
  },
  created() {
    this.id = this.$cookies.get('id')


    this.$axios.get(this.$settings.BASE_URL + 'address/default/?user_id=' + this.id,
      {headers: {'Authorization': 'jwt ' + this.$cookies.get('token')}}).then(res => {
      if (res.code == 100) {
        this.name = res.result.name,
          this.tel = res.result.tel,
          this.province_name = res.result.province_name,
          this.city_name = res.result.city_name,
          this.region_name = res.result.region_name,
          this.detail_address = res.result.detail_address,
          this.defaultID = res.result.id
      }
    })
    let _province_list = {}
    let _city_list = {}
    let _county_list = {}
    tdist.getLev1().forEach(p => {
      _province_list[p.id] = p.text
      tdist.getLev2(p.id).forEach(c => {
        _city_list[c.id] = c.text
        tdist.getLev3(c.id).forEach(q => _county_list[q.id] = q.text)
      })
    })
    this.areaList.province_list = _province_list
    this.areaList.city_list = _city_list
    this.areaList.county_list = _county_list
    const {type, from, addressId} = this.$route.query
    this.addressId = addressId
    this.type = type
    this.from = from || ''
    if (type == 'edit') {
      this.$axios.get(this.$settings.BASE_URL + 'address/detail/' + this.addressId + '/',
        {headers: {'Authorization': 'jwt ' + this.$cookies.get('token')}}).then(res => {
        const province = tdist.getLev1()
        let _areaCode = ''
        Object.entries(this.areaList.county_list).forEach(([id, text]) => {
          // 先找出当前对应的区
          if (text == res.region_name) {
            // 找到区对应的几个省份
            const provinceIndex = province.findIndex(item => item.id.substr(0, 2) == id.substr(0, 2))
            // 找到区对应的几个市区
            const cityItem = Object.entries(this.areaList.city_list).filter(([cityId, cityName]) => cityId.substr(0, 4) == id.substr(0, 4))[0]
            // 对比找到的省份和接口返回的省份是否相等，因为有一些区会重名
            if (province[provinceIndex].text == res.province_name && cityItem[1] == res.city_name) {
              _areaCode = id
            }
          }
        })
        this.addressInfo = {
          id: res.addressId,
          name: res.name,
          tel: res.tel,
          province: res.provinceName,
          city: res.city_name,
          county: res.region_name,
          areaCode: _areaCode,
          addressDetail: res.detail_address,
          isDefault: !!res.isDefault
        }
      })
    }

  },
  methods: {
    onSave(content) {
      if (this.type == 'add') {
        if (content.isDefault) {
          this.$axios.put(this.$settings.BASE_URL + 'address/detail/' + this.defaultID + '/?user_id=' + this.id, {
            name: this.name,
            tel: this.tel,
            province_name: this.province_name,
            city_name: this.city_name,
            region_name: this.region_name,
            detail_address: this.detail_address,
            isDefault: 0,
            ship_address: 0,
            user: this.id,
          }, {headers: {'Authorization': 'jwt ' + this.$cookies.get('token')}}).then(res => {
          })
          this.$axios.post(this.$settings.BASE_URL + 'address/detail/?user_id=' + this.id, {
              name: content.name,
              tel: content.tel,
              province_name: content.province,
              city_name: content.city,
              region_name: content.county,
              detail_address: content.addressDetail,
              isDefault: content.isDefault ? 1 : 0,
              user: this.id,
              ship_address: content.isDefault ? 1 : 0,
            }, {headers: {'Authorization': 'jwt ' + this.$cookies.get('token')}}
          ).then(res => {
            if (res.code == 100) {
              this.$store.dispatch('deafultAddress',
                [content.name, content.tel, content.province, content.city, content.county, content.addressDetail, res.result.id]
              )
              Toast.success('保存成功')
              this.$router.go(-1)
            } else {
              Toast.fail('保存失败')
            }
          })
        } else {
          this.$axios.get(this.$settings.BASE_URL + 'address/detail/?user_id=' + this.id,
            {headers: {'Authorization': 'jwt ' + this.$cookies.get('token')}}
          ).then(
            res => {
              if (res.result.length > 0) {
                this.$axios.post(this.$settings.BASE_URL + 'address/detail/?user_id=' + this.id, {
                    name: content.name,
                    tel: content.tel,
                    province_name: content.province,
                    city_name: content.city,
                    region_name: content.county,
                    detail_address: content.addressDetail,
                    isDefault: content.isDefault ? 1 : 0,
                    ship_address: 0,
                    user: this.id,
                  }, {headers: {'Authorization': 'jwt ' + this.$cookies.get('token')}}
                ).then(res => {
                  if (res.code == 100) {
                    this.$store.dispatch('deafultAddress',
                      [content.name, content.tel, content.province, content.city, content.county, content.addressDetail, res.result.id]
                    )
                    Toast.success('保存成功')
                    this.$router.go(-1)
                  } else {
                    Toast.fail('保存失败')
                  }
                })
              }else{
                        this.$axios.post(this.$settings.BASE_URL + 'address/detail/?user_id=' + this.id, {
                    name: content.name,
                    tel: content.tel,
                    province_name: content.province,
                    city_name: content.city,
                    region_name: content.county,
                    detail_address: content.addressDetail,
                    isDefault: 1,
                    ship_address: 0,
                    user: this.id,
                  }, {headers: {'Authorization': 'jwt ' + this.$cookies.get('token')}}
                ).then(res => {
                  if (res.code == 100) {
                    this.$store.dispatch('deafultAddress',
                      [content.name, content.tel, content.province, content.city, content.county, content.addressDetail, res.result.id]
                    )
                    Toast.success('保存成功')
                    this.$router.go(-1)
                  } else {
                    Toast.fail('保存失败')
                  }
                })
              }
            }
          )


        }
      } else {
        if (content.isDefault) {
          this.$axios.put(this.$settings.BASE_URL + 'address/detail/' + this.defaultID + '/?user_id=' + this.id, {
            name: this.name,
            tel: this.tel,
            province_name: this.province_name,
            city_name: this.city_name,
            region_name: this.region_name,
            detail_address: this.detail_address,
            isDefault: 0,
            ship_address: 0,
            user: this.id,
          }, {headers: {'Authorization': 'jwt ' + this.$cookies.get('token')}}).then(res => {
          })
        }
        this.$axios.put(this.$settings.BASE_URL + 'address/detail/' + this.addressId + '/?user_id=' + this.id, {
          name: content.name,
          tel: content.tel,
          province_name: content.province,
          city_name: content.city,
          region_name: content.county,
          detail_address: content.addressDetail,
          isDefault: content.isDefault ? 1 : 0,
          ship_address: content.isDefault ? 1 : 0,
          user: this.id,
        }, {headers: {'Authorization': 'jwt ' + this.$cookies.get('token')}})
          .then(res => {
            if (res.code == 100) {
              this.$store.dispatch('deafultAddress',
                [content.name, content.tel, content.province, content.city, content.county, content.addressDetail, res.result.id]
              )
              Toast.success('修改成功')
              this.$router.go(-1)
            } else {
              Toast.fail('修改失败')
            }
          })
      }
      setTimeout(() => {
        this.$router.push({path: `address?from=${this.from}`})
      }, 1000)
    },
    onDelete() {
      this.$axios.delete(this.$settings.BASE_URL + 'address/detail/' + this.addressId + '/',
        {headers: {'Authorization': 'jwt ' + this.$cookies.get('token')}}).then(res => {
        Toast('删除成功')
        setTimeout(() => {
          this.$router.push({path: 'address'})
        }, 1000)
      })
    }
  }
}
</script>

<style lang="less">
@import '../common/style/mixin';

.address-edit-box {
  margin-top: 44px;

  .van-address-edit {
    .van-button--danger {
      background: @primary;
      border-color: @primary;
    }

    .van-switch--on {
      background: @primary;
    }
  }
}
</style>
